<?php

/**
 * @author Nemo <nemo.xiaolan@gmail.com>
 */
/**
 * 实现简易的插件机制
 * 
 * @package lib.org.pluggable
 */
class Pluggable {

    static public $hooks = array();

    static public $plugins = array();
    
    static public function init() {
        $dir = PROJECT_DIR.DS."plugins";
        $handler = opendir($dir);
        if($handler) {
            while (($filename = readdir($handler)) !== false) {
                if($filename != '.' and $filename != '..' and is_file($filename)) {
                    require $dir.DS.$filename;
                }
            }
            closedir($handler);
        }
    }

    /**
     * Pluggable::register()
     * @param array $callable
     * @param string $hook
     * @return void
     *
     */
    static public function register($callable, $hook, $package = null) {
        list($class, $method,) = $callable;
        self::$plugins[$hook][] = array($class, $method, $package);
    }

    /**
     * Pluggable::trigger();
     *
     * @param $hook string
     * @return void
     *
     * trigger the hook
     */
    static public function trigger($hook, $params = array()) {
        
    	if(!self::$plugins[$hook]) {
    	    return false;
    	}
    	
    	foreach(self::$plugins[$hook] as $callable) {
    	    list($class_name, $method, $package) = $callable;
	        if(!class_exists($class_name)) {
	            continue;
	        }
	        if(!has_static_method($class_name, $method)) {
	            $class = new $class_name;
	        } else {
	            $class = $class_name;
	        }
	        call_user_func_array(
	            array($class, $method), $params
	        );
    	}
    }
}